package com.attilax.cmsPoster;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

//import org.eclipse.swt.layout.FillLayout;
//import org.eclipse.swt.widgets.Display;
//import org.eclipse.swt.widgets.Shell;
import org.openqa.selenium.firefox.FirefoxDriver;

import aaaBlogger.img.Ipub2;

import com.attilax.Closure;
import com.attilax.core;
import com.attilax.formH5.BrowserForm;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.Global;
import com.attilax.text.strUtil;
import com.attilax.util.PropX;
//import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

//import org.junit.*;

//import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;
import org.openqa.selenium.support.ui.Select;


/**
 * com.attilax.cmsPoster.BlogPubberMainform.startOpenBlogs
 * @author attilax
 *2016年5月14日 上午12:12:19
 */
public class BlogPubber {

	public static void main(String[] args) {
//		BlogPubberMainform ef = new BlogPubberMainform();
// 		ef.setSize(1200, 700);
// 		ef.show();
// 	ef.threadRecycle();

	}
	String baseDir;
	@SuppressWarnings("all")
	public BlogPubber() {
		baseDir = pathx.classPathParent_jensyegeor() + "/blogger";
		String urlgoto = baseDir + "/index.html";  //   /blogger/index.html
	//	ini(urlgoto);
	}
 
	
	/**
	attilax    2016年5月14日  上午12:09:01
	 */
	public void startOpenBlogs() {
		HttpServletRequest req = Global.req.get();
		String p1tit = (String) req.getParameter("tit");
		String p2_txt = (String)req.getParameter("txt");
		System.out.println(p1tit + p2_txt);
		select_ids = (String)req.getParameter("sites");

	 
		submitx(p1tit, p2_txt);

	}
	private String select_ids;

	

	protected void submitx(String p1tit, String p2_txt) {
		System.setProperty("webdriver.firefox.bin", pathx.classPathParent()
				+ "\\Mozilla Firefox\\firefox.exe");

		@SuppressWarnings("unchecked")
		List<String> li = filex.read2list_filtEmptyNstartSpace(baseDir+ "/db/index.txt");
		li=strUtil.toList(select_ids, ",");
		//sql dsl select 
		for (String line : li) {
			
			try {
				if(line.trim().startsWith("#"))
					continue;
				if(line.trim().equals("nonex"))
					continue;
				if(line.trim().equals("null"))
					continue;
				String cfg_path = baseDir+ "/db/" + line
						+ "/cfg.txt";
				PropX px = new PropX(cfg_path, "gbk");
				Global.propMap.put(line.trim(), px);
				submit_single(p1tit, p2_txt,line); //sql dsl insert
				System.out.println(cfg_path);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}

	}

	private void submit_single(final String p1tit,final String p2_txt, final String blogName) {
		System.out.println("");
		core.execMeth_Ays(new Runnable() {
			
			@SuppressWarnings("static-access")
			@Override
			public void run() {
				
				Global.blogName.set(blogName);
			//	BlogPubberMainform.this.blogName.get()
				FirefoxDriver driver =null;
				try {
					driver=(FirefoxDriver) Global.propMap.get(blogName+"_driver");
					if(isDisconn(driver))
						driver=null;
				} catch (Exception e) {
					// TODO: handle exception
				}
			
				if (driver == null)
				{
					String ffpath = pathx.webAppPath()
							+ "\\Mozilla Firefox\\firefox.exe";
					System.setProperty("webdriver.firefox.bin", ffpath);
					driver = new FirefoxDriver();
					Global.propMap.put(blogName+"_driver",driver);
				}
				try {
					// String baseUrl="http://write.blog.csdn.net/postedit";

					closeAlert(driver);
					PropX px=(PropX) Global.propMap.get(blogName);
					String pubUrl =px.getProperty("pub_url");
				//	String blog_index=px.getProperty("blog_index");
					
					try{
						if (!driver.getCurrentUrl().equals(pubUrl))
							driver.get(pubUrl);
				   } catch(org.openqa.selenium.UnhandledAlertException e){
						closeAlert(driver);
						if (!driver.getCurrentUrl().equals(pubUrl))
							driver.get(pubUrl);
				         // you logic here what you want to do next
				      }  
				
					String sou = driver.getPageSource();
					String title = driver.getTitle();
					driverPb3=driver;
					if (isInLoginForm(title, sou)) {
						// String baseUrl="http://write.blog.csdn.net/postedit";
						// driver.get(baseUrl );
						login(driver,blogName);

					}
					  sou = driver.getPageSource();
//						JavascriptExecutor jse = (JavascriptExecutor) driver;
//						Object obj=		driver.executeScript("	return document.title; ",
//								driver.findElement(By.id("editor")));
					//  title = (String) obj;
							  //driver.getTitle();jeig yaosi manu op ..laoxsh outtime value ..
					while(true)						
					{
						title=driver.getTitle();
						if(isInLoginForm(title,sou))
						Thread.sleep(3000);
						else
							break;
					}
					publish(p1tit, p2_txt, driver,blogName);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}, "threadName"+blogName);
		
	}

	protected boolean isDisconn(FirefoxDriver driver) {
		try {
			System.out.println(driver.getCurrentUrl());
		} catch (UnreachableBrowserException e) {
			return true;
		}catch(WebDriverException e)
		{
			return true;
		}
		
		return false;
	}

	private void closeAlert(FirefoxDriver driver) {
		try {
			
		//JavaScriptExecutor js = (JavaScriptExecutor)driver;
			// Override window.alert to store the prompt and accept it automatically
		 // j
		String js="window.alert = function(msg) { document.bAlert = true; document.lastAlert=msg; }";
		driver.executeScript(js, driver.findElement(By.tagName("body")));
		//	js.ExecuteScript();
			Alert alert = driver.switchTo().alert();
			// Get the text from the alert

			String alertText = alert.getText();
			// Accept the alert
			alert.accept();
			try {
				alert.dismiss();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} catch (NoAlertPresentException e) {
			 System.out.println("There is no alert appear!");  

		}catch(UnreachableBrowserException e)
		{
			renewBrowser(Global.blogName.get());
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	
	private void renewBrowser(String blogger) {
		FirefoxDriver	driver = new FirefoxDriver();
		Global.propMap.put(blogger+"_driver",driver);
		
	}

	//private String loginUrl = "http://passport.csdn.net/account/login";
//	public  String blogName;
 //public static	 ThreadLocal<String> blogNameThreadLocal = new ThreadLocal<String>();

	private void publish(String p1tit, String p2_txt, FirefoxDriver driver, String blogName) {
		
		if(blogName.equals("nonex"))
			return ;
		PropX px=(PropX) Global.propMap.get(blogName);
		String pubUrl =px.getProperty("pub_url");
		if (!driver.getCurrentUrl().equals(pubUrl))
			driver.get(pubUrl);
		// driver.findElement(By.cssSelector("#btnWrite > a > span")).click();
		// driver.findElement(By.cssSelector("span.close")).click();
		// driver.findElement(By.id("selType")).click();
		String pubber=px.getProperty("pubber");
		
		Ipub puber = (Ipub) core.newx((pubber));
		
		puber.pub2(p1tit, p2_txt, driver);
	}

//	private void pub2(String p1tit, String p2_txt, FirefoxDriver driver) {
//		
//	}
	FirefoxDriver driverPb3;
	private void login(FirefoxDriver driver, String blogName) {
		driverPb3=driver;
		//pb3 add recomm  tony fangdaog yg login url hto  k..
		if (isInLoginForm(driver.getTitle(), driver.getPageSource())) {
			PropX px=(PropX)Global. propMap.get(blogName );
			String loginUrl =px.getProperty("login_url");
			driver.get(loginUrl);
		}
		PropX px=(PropX)Global. propMap.get(blogName);
	    String pubber=px.getProperty("pubber");
		
		Ipub puber = (Ipub) core.newx((pubber));
		
		//pb3
//		try {
//			Ipub2 puber2 =(Ipub2) puber;
//			if(puber2.isInLoginForm(driver.getTitle(), driver.getPageSource()))
//			{
//				PropX px2=(PropX) propMap.get(blogName );
//				String loginUrl =px2.getProperty("login_url");
//				driver.get(loginUrl);
//			}
//		} catch (ClassCastException e) {
//			// TODO: handle exception
//		}
		
		
		puber.login( driver,px);
		
		// driver.findElement(By.id("rememberMe")).click();
		// driver.findElement(By.cssSelector("input.logging")).click();
	}

	private boolean isInLoginForm(String title, String sou) {

		//blogName.get()
		PropX px = (PropX) Global.propMap.get(Global.blogName.get());
		String pubber = px.getProperty("pubber");

		Ipub puber = (Ipub) core.newx((pubber));
		// pb3
		FirefoxDriver driver = driverPb3;
		try {
			Ipub2 puber2 = (Ipub2) puber;
			return (puber2.isInLoginForm(driver.getTitle(),
					driver.getPageSource()));

		} catch (ClassCastException e) {
			return isInLoginForm_ori(title);
		}

	}

	private boolean isInLoginForm_ori(String title) {
		PropX px=(PropX)Global. propMap.get(Global.blogName.get());
		String loginFormStr =px.getProperty("loginFormStr");
		
		//if (title.equals(loginFormStr))
		Set<String> set=strUtil.toSet(loginFormStr.trim());
		if(set.contains(title))
			return true;
		return false;
	}

	// private boolean isInLoginForm(FirefoxDriver driver) {
	//
	// return false;
	// }

}
